import base64
import requests
from res.url import ResUrl
import base64
import urllib
from os import path
import cv2


class OcrEngine:
    def __init__(self):
        self.api_key = "lCDZReZ2HGTUdMiqM9yuzCsU"
        self.secret_key = "MUb7Y6VQtk1kLtqdLGkVGzF8iLUwRaEZ"
        self.request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic"
        self.access_token = self.fetch_token()

    def fetch_token(self):
        host = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={0}&client_secret={1}".format(
            self.api_key, self.secret_key)
        response = requests.get(host).json()
        return response["access_token"]

    def do(self, image):
        try:
            img_str = cv2.imencode('.jpg', image)[1].tostring()
            img = base64.b64encode(img_str)
            params = {"image": img,
                      "is_sync": "true",
                      "request_type": "excel"}
            request_url = self.request_url + "?access_token=" + self.access_token
            headers = {'content-type': 'application/x-www-form-urlencoded'}
            response = requests.post(request_url, data=params, headers=headers).json()
            text = response["words_result"][0]["words"]
            return text
        except:
            return ""


ocr_engine = OcrEngine()
